<?php
/**
 * 短信发送类:平台创蓝
 * 2019.7.23
 * QQ:748507607
 * 备注: 测试号码不加白名单限制为:给一个号码发短信,1分钟收到2条,一小时5条,一天限制10条
 */
namespace app\common\model;

use Config;
class SendSms
{	
	/**
	 * 发送短信	 *
	 * @param string $mobile 		手机号码
	 * @param string $msg 			短信内容
	 * @param string $needstatus 	是否需要状态报告
	 */
	public function sendSms( $mobile, $msg, $needstatus = 'true') {		
		//创蓝接口参数
        $msg = '您的验证码是' . $msg . ',30分钟内有效';
		$postArr = array (
			'account'  =>  config('send_sms')['api_account'],
			'password' =>  config('send_sms')['api_password'],
			'msg' => urlencode($msg),
			'phone' => $mobile,
			'report' => $needstatus
        );
		$result = $this->curlPost( config('send_sms')['api_send_url'],$postArr );		
		if(!is_null(json_decode($result))){	
	        $output=json_decode($result,true);
	        if(isset($output['code'])  && $output['code']=='0'){
//                returnJson(200,"短信发送成功")->send();
	        }else{
                returnJson(-1004,$output['errorMsg'])->send();die;
	        }
       }else{
            returnJson(-1004,$result)->send();die;
       }
	}
	/**
	 * 通过CURL发送HTTP请求
	 * @param string $url  //请求URL
	 * @param array $postFields //请求参数 
	 * @return mixed
	 *  
	 */
	private function curlPost( $url,$postFields ){
		$postFields = json_encode( $postFields );
		
		$ch = curl_init ();
		curl_setopt( $ch, CURLOPT_URL, $url ); 
		curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json; charset=utf-8'   
			)
		);
		curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt( $ch, CURLOPT_TIMEOUT,60); 
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
		$ret = curl_exec ( $ch );
        if (false == $ret) {
            $result = curl_error(  $ch);
        } else {
            $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 ". $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
		curl_close ( $ch );
		return $result;
	}



}	